<template>
  <el-upload action="" :show-file-list="false" :file-list="uploadFileList" :on-remove="Remove" :auto-upload="false" :on-change="handleChange">
    <template #default>
      <p>{{ typeData.name }}</p>
    </template>
    <template #file="{ file }">
      <div>
        {{ file }}
      </div>
    </template>
  </el-upload>
</template>
<script lang="ts" setup>
  import { uploadFile2 } from '@/api/common'
  import { importTemplate } from '@/api/employe/employeetasks/taskmanage'
  import { reactive, ref, withDefaults, defineProps, defineEmits } from 'vue'
  import { ElMessage } from 'element-plus'

  const uploadFileList = ref([])

  interface Props {
    typeData: any
  }
  const props = withDefaults(defineProps<Props>(), {
    typeData: () => ({ type: 1, object_type: 1, name: '个人客户模板' })
  })
  const rule = reactive({
    type: 'xlsx|XLSX',
    unit: 'MB',
    size: 20
  })
  const emit = defineEmits(['submit'])
  let ext = ref()
  const uploadImg = async (file: any) => {
    file = file.raw
    ext.value = file.name.substring(file.name.lastIndexOf('.'))
    return await uploadFile2({
      file,
      fileName: file.name
    })
  }
  const handleChange = async (file: any) => {
    const fileName = file.name.split('.')
    if (!rule.type.includes(fileName.pop())) {
      ElMessage.error('上传文件类型不正确, 请重新上传!')
      return
    }
    if (rule.unit === 'MB') {
      if (file.size / 1024 / 1024 > rule.size) {
        ElMessage.error('文件大小不能超过' + rule.size + 'MB')
        return
      }
    }
    const data: any = await uploadImg(file)
    console.log('导入文件', data)
    const form = new FormData()
    form.append('file', file.raw)
    form.append('type', props.typeData.object_type) // 线索/客户
    form.append('role_type', props.typeData.type) // 个人/企业
    form.append('code', data.code)
    form.append('url', data.url)
    importTemplate(form).then((res: any) => {
      emit('submit', { ...res, name: file.name })
    })
  }
  const Remove = (file: UploadFile, list: UploadFile[]) => {
    uploadFileList.value = list
    emit('submit', list)
    // bus.emit('empty')
    console.log(file, list, '===自动删除')
  }
  defineExpose({
    uploadFileList
  })
</script>
<style lang="scss" scoped></style>
